import request from '@/utils/request'
import auth from '@/utils/auth'

// 药品订单相关接口
export const orderMedicineApi = {
  // 创建订单
  createOrder(data) {
    return request({
      url: '/api/orderMedicine/create',
      method: 'POST',
      data
    })
  },

  // 获取订单列表
  getOrderList(params) {
    try {
      // 参数验证
      if (!params.userId) {
        throw new Error('缺少必需的参数: userId');
      }

      // 确保参数都是字符串类型
      const requestParams = {
        userId: String(params.userId),
        status: params.status !== undefined ? String(params.status) : '',
        page: String(params.page || 1),
        pageSize: String(params.pageSize || 10),
        timestamp: String(new Date().getTime())
      };

      console.log('获取订单列表，参数:', requestParams);

      return request({
        url: '/api/orderMedicine/list',
        method: 'GET',
        params: requestParams,
        transformResponse: [(data) => {
          try {
            // 记录原始响应数据
            console.log('订单列表原始响应:', data);
            
            // 如果已经是对象，直接返回
            if (typeof data === 'object') {
              console.log('响应数据已经是对象:', data);
              return data;
            }

            // 解析字符串响应
            if (typeof data === 'string') {
              // 直接解析，不做任何转换
              const jsonData = JSON.parse(data);
              console.log('解析后的响应数据:', jsonData);

              // 记录订单ID的类型信息
              if (jsonData.data && Array.isArray(jsonData.data)) {
                jsonData.data.forEach((order, index) => {
                  console.log(`订单[${index}] ID信息:`, {
                    订单ID: order.orderId,
                    类型: typeof order.orderId,
                    长度: String(order.orderId).length
                  });
                });
              }

              return jsonData;
            }

            return data;
          } catch (e) {
            console.error('转换响应数据失败:', e);
            return data;
          }
        }]
      });
    } catch (error) {
      console.error('获取订单列表失败:', error);
      throw error;
    }
  },

  // 获取订单详情
  getOrderDetail(orderId) {
    try {
      // 参数验证
      if (!orderId) {
        throw new Error('缺少必需的参数: orderId');
      }

      // 确保订单ID是字符串
      const orderIdStr = String(orderId);
      console.log('获取订单详情:', {
        原始订单ID: orderId,
        处理后订单ID: orderIdStr,
        类型: typeof orderIdStr
      });

      return request({
        url: `/api/orderMedicine/${orderIdStr}`,
        method: 'GET',
        transformResponse: [(data) => {
          try {
            // 使用 reviver 确保大整数作为字符串处理
            return typeof data === 'string' ? JSON.parse(data, (key, value) => {
              if (key === 'orderId' && typeof value === 'number') {
                return String(value);
              }
              return value;
            }) : data;
          } catch (e) {
            return data;
          }
        }]
      });
    } catch (error) {
      console.error('获取订单详情失败:', error);
      throw error;
    }
  },

  // 获取订单项
  getOrderItems(orderId) {
    return request({
      url: `/api/orderMedicine/${orderId}/items`,
      method: 'GET'
    })
  },

  // 取消订单
  cancelOrder(params) {
    return request({
      url: '/api/orderMedicine/cancel',
      method: 'POST',
      data: params,
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },

  // 支付订单
  async payOrder(params) {
    try {
      if (!params || !params.orderId) {
        throw new Error('缺少必需的参数: orderId');
      }

      // 确保订单号是字符串类型
      const orderId = String(params.orderId).replace(/\.0+$/, ''); // 移除可能存在的小数点和尾随零
      
      // 构建请求参数
      const requestParams = {
        orderId: orderId,
        paymentType: params.paymentType || 'WECHAT',
        totalFee: params.totalFee
      };

      console.log('支付请求参数:', {
        原始订单号: params.orderId,
        处理后订单号: orderId,
        订单号类型: typeof orderId,
        完整参数: requestParams
      });

      // 发送请求
      const response = await request({
        url: '/api/orderMedicine/pay',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: requestParams
      });

      console.log('支付接口原始响应:', response);

      if (!response || response.code !== 200) {
        throw new Error(response?.errorMessage || '获取支付二维码失败');
      }

      return {
        code: response.code,
        data: {
          qrCodeImage: response.data?.codeUrl || response.data?.qrCodeImage,
          outTradeNo: response.data?.outTradeNo || response.data?.orderNo,
          orderId: orderId
        },
        errorMessage: response.errorMessage
      };
    } catch (error) {
      console.error('支付请求失败:', error);
      throw error;
    }
  },

  // 检查支付状态
  async checkPayStatus(params) {
    try {
      if (!params || !params.outTradeNo) {
        throw new Error('缺少必需的参数: outTradeNo');
      }

      const response = await request({
        url: '/api/orderMedicine/checkPayStatus',
        method: 'GET',
        params: {
          outTradeNo: params.outTradeNo,
          orderId: params.orderId, // 可选参数
          timestamp: new Date().getTime() // 添加时间戳防止缓存
        }
      });

      console.log('检查支付状态响应:', response);

      if (!response) {
        throw new Error('查询支付状态失败：未收到响应');
      }

      if (response.code !== 200) {
        throw new Error(response.errorMessage || '查询支付状态失败');
      }

      // 规范化返回数据
      return {
        code: response.code,
        status: response.data || 'UNKNOWN',
        message: response.errorMessage || '查询成功'
      };
    } catch (error) {
      console.error('查询支付状态失败:', error);
      throw error;
    }
  },

  // 确认收货
  confirmReceive(orderId) {
    return request({
      url: '/api/orderMedicine/confirm',
      method: 'POST',
      data: { orderId }
    })
  },

  // 删除订单
  deleteOrder(orderId) {
    return request({
      url: '/api/orderMedicine/delete',
      method: 'POST',
      data: { orderId }
    })
  },

  // 获取订单状态数量统计
  getOrderCounts(userId) {
    return request({
      url: '/api/orderMedicine/counts',
      method: 'GET',
      params: { userId }
    })
  }
}
